﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace LearnCSharp.SqlMap.Extension
{
    public class TableInfo
    {
        private TableInfo() { }
        public TableInfo(string className, IList<FieldInfo> fieldInfos)
        {
            this._className = className;
            _fieldDict = fieldInfos.GroupBy(a => a.PropertyInfo.Name)
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }

        public Type Type { get; set; }
        private string _className { get; set; }
        private string _tableName { get; set; }


        public string TableName
        {
            get
            {
                if (string.IsNullOrEmpty(_tableName))
                {
                    return _className;
                }

                return _tableName;
            }
            set
            {
                if (_tableName == value) return;
                _tableName = value;
            }
        }

        public IList<FieldInfo> Fields
        {
            get
            {
                return _fieldDict.Select(a => a.Value).ToList();
            }
        }

        public Dictionary<string, FieldInfo> _fieldDict { get; private set; }

        public FieldInfo GetFieldInfo(string propertyName)
        {
            _fieldDict.TryGetValue(propertyName, out var field);
            return field;
        }
    }
}
